package flc.ast.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.thanosfisherman.wifiutils.WifiUtils;
import com.thanosfisherman.wifiutils.wifiConnect.ConnectionErrorCode;
import com.thanosfisherman.wifiutils.wifiConnect.ConnectionSuccessListener;

import java.util.ArrayList;
import java.util.List;

import flc.ast.R;
import flc.ast.activity.PasswordGenerateActivity;
import flc.ast.activity.WifiSecurityActivity;
import flc.ast.activity.WifiSignalActivity;
import flc.ast.adapter.WifiAdapter;
import flc.ast.bean.MyWifiBean;
import flc.ast.databinding.FragmentHomeBinding;
import flc.ast.dialog.PasswordDialog;
import flc.ast.dialog.PasswordViewDialog;
import flc.ast.dialog.RandomNumberDialog;
import flc.ast.dialog.TurnDialog;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.basic.utils.WiFiUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends BaseNoModelFragment<FragmentHomeBinding> {

    private List<MyWifiBean> listShow = new ArrayList<>();
    private WifiAdapter wifiAdapter;
    private int selPosition;

    @Override
    protected int onCreate() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event1Container);

        mDataBinding.llPasswordView.setOnClickListener(this);
        mDataBinding.llPasswordGenerate.setOnClickListener(this);
        mDataBinding.llRandomNumber.setOnClickListener(this);
        mDataBinding.llWifiSignal.setOnClickListener(this);
        mDataBinding.llWifiSecurity.setOnClickListener(this);
        mDataBinding.tvRefresh.setOnClickListener(this);
        mDataBinding.tvWifiNoPermission.setOnClickListener(this);


        mDataBinding.rvWifiList.setLayoutManager(new LinearLayoutManager(mContext));
        wifiAdapter = new WifiAdapter();
        mDataBinding.rvWifiList.setAdapter(wifiAdapter);
        wifiAdapter.addChildClickViewIds(R.id.tvWifiItemConnect);
        wifiAdapter.setOnItemChildClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.llPasswordView://密码查看
                showPasswordViewDialog();
                break;
            case R.id.llPasswordGenerate://密码生成
                startActivity(PasswordGenerateActivity.class);
                break;
            case R.id.llRandomNumber://随机数
                showRandomNumberDialog();
                break;
            case R.id.llWifiSignal://wifi信号
                startActivity(WifiSignalActivity.class);
                break;
            case R.id.llWifiSecurity://wifi安全
                startActivity(WifiSecurityActivity.class);
                break;
            case R.id.tvRefresh://刷新
                getWifiData();
                break;
            case R.id.tvWifiNoPermission://无权限
                getPermission();
                break;
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.tvWifiItemConnect://连接
                selPosition = position;
                if (wifiAdapter.getItem(position).isOpened()) {
                    connWifi(wifiAdapter.getItem(position).getName(), "");
                } else {
                    showPasswordDialog();
                }
                break;
        }
    }

    @Override
    protected void initData() {
        checkPermission();
    }

    private void checkPermission() {
        if (PermissionUtils.isGranted(Manifest.permission.ACCESS_FINE_LOCATION)) {
            mDataBinding.rvWifiList.setVisibility(View.VISIBLE);
            mDataBinding.llWifiNoPermission.setVisibility(View.GONE);
            getPermission();
        } else {
            mDataBinding.rvWifiList.setVisibility(View.GONE);
            mDataBinding.llWifiNoPermission.setVisibility(View.VISIBLE);
            mDataBinding.tvWifiName.setText(getString(R.string.no_connect));
            mDataBinding.tvWifiNum.setText(getString(R.string.wifi_num, 0));
        }
    }

    private void getPermission() {
        StkPermissionHelper.permission(Manifest.permission.ACCESS_FINE_LOCATION)
                .reqPermissionDesc(getString(R.string.get_location_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        if (NetworkUtils.isWifiConnected()) {
                            mDataBinding.tvWifiName.setText(getString(R.string.connected_tip) + NetworkUtils.getSSID());
                        } else {
                            mDataBinding.tvWifiName.setText(getString(R.string.no_connect));
                        }
                        getWifiData();
                    }
                }).request();
    }

    //获取wifi列表
    private void getWifiData() {
        listShow.clear();
        @SuppressLint("MissingPermission") NetworkUtils.WifiScanResults wifiScanResult = NetworkUtils.getWifiScanResult();
        List<ScanResult> filterResults = wifiScanResult.getFilterResults();
        for (ScanResult bean : filterResults) {
            boolean isOpened = WiFiUtil.isOpened(bean);
            if (bean.SSID.equals(NetworkUtils.getSSID())) {
                listShow.add(new MyWifiBean(bean.SSID, isOpened, true));
            } else {
                listShow.add(new MyWifiBean(bean.SSID, isOpened, false));
            }
        }
        if (listShow.size() > 0) {
            wifiAdapter.setList(listShow);
            mDataBinding.rvWifiList.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.rvWifiList.setVisibility(View.GONE);
        }
        mDataBinding.tvWifiNum.setText(getString(R.string.wifi_num, listShow.size()));
        mDataBinding.llWifiNoPermission.setVisibility(View.GONE);
    }

    //连接wifi
    private void connWifi(String wifiName, String wifiPassword) {
        showDialog(getString(R.string.conn_wifi_ing));
        WifiUtils.withContext(mContext)
                .connectWith(wifiName, wifiPassword)
                .setTimeout(40000)
                .onConnectionResult(new ConnectionSuccessListener() {
                    @Override
                    public void success() {
                        for (MyWifiBean bean : wifiAdapter.getValidData()) {
                            bean.setConnect(false);
                        }
                        wifiAdapter.getItem(selPosition).setConnect(true);
                        wifiAdapter.notifyDataSetChanged();
                        mDataBinding.tvWifiName.setText(NetworkUtils.getSSID());
                        dismissDialog();
                    }

                    @Override
                    public void failed(@NonNull ConnectionErrorCode errorCode) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.password_def);
                    }
                })
                .start();
    }

    private void showPasswordDialog() {
        PasswordDialog dialog = new PasswordDialog(mContext);
        dialog.title = wifiAdapter.getItem(selPosition).getName();
        dialog.setListener(new PasswordDialog.Ilistener() {

            @Override
            public void click(String password) {
                connWifi(wifiAdapter.getItem(selPosition).getName(), password);
            }

        });
        dialog.show();
    }

    private void showPasswordViewDialog() {
        PasswordViewDialog dialog = new PasswordViewDialog(mContext);
        dialog.setListener(new PasswordViewDialog.Ilistener() {

            @Override
            public void click() {
                showTurnDialog();
            }

        });
        dialog.show();
    }

    private void showTurnDialog() {
        TurnDialog dialog = new TurnDialog(mContext);
        dialog.setListener(new TurnDialog.Ilistener() {

            @Override
            public void click() {
                Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                startActivity(intent);
            }

        });
        dialog.show();
    }

    private void showRandomNumberDialog() {
        RandomNumberDialog dialog = new RandomNumberDialog(mContext);
        dialog.show();
    }

}